package com.sc.socket.tcpdemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @author shuc001
 * @Date 2019-02-01 21:18
 */
public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket();
        socket.setSoTimeout(3000);
        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(),2000));
        System.out.println("连接完成");
        try {
            todo(socket);
        }catch (Exception e){
            e.printStackTrace();
        }
        socket.close();
        System.out.println("客户端退出");
    }

    private static void todo(Socket socket) throws IOException {
        InputStream in = System.in;
        BufferedReader input = new BufferedReader(new InputStreamReader(in));
        //得到socket输出流,打印
        OutputStream outputStream = socket.getOutputStream();
        PrintStream printStream = new PrintStream(outputStream);

        InputStream inputStream = socket.getInputStream();
        BufferedReader sbuff = new BufferedReader(new InputStreamReader(inputStream));

        boolean  flag=true;
        do {
            String str = input.readLine();
            printStream.println(str);

            String ret = sbuff.readLine();
            if ("bye".equalsIgnoreCase(ret)) {
                flag=false;
            }else{
                System.out.println(ret);
            }
        }while (flag);
        sbuff.close();
        inputStream.close();
    }
}
